<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus';

import { deviceInventoryApi } from '@/pages/deviceUse/components/DeviceRepo';
import type { Category,DeviceAttachmentDTO,DeviceAttachment,DeviceInventory, DeviceInventoryModel, DeviceInventoryListResponse, DeviceInventoryFormItemConfig } from "@/pages/deviceUse/components/DeviceRepo";
import { useTokenStore } from '@/stores/token'
const formRef = ref<FormInstance>();

const formRules: FormRules = {
  deviceName: [
    { required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }
  ],
  deviceModel: [
    { required: true, message: '设备型号不能为空',trigger: ['blur', 'change']}
  ],
  category: [
    { required: true, message: '类别不能为空', trigger: ['blur', 'change']}
  ],
  supplier: [
    { required: true, message: '供应商不能为空', trigger: ['blur', 'change'] }
  ],
  supplierScore: [
    { required: true, message: '供应商评分不能为空', trigger: ['blur', 'change']},
    {
      validator: (_rule, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) {
          callback(new Error('评分必须为数字'));
        } else if (num < 0 || num > 100) {
          callback(new Error('评分应在 0 ~ 100 之间'));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change'],
    }
  ]
};


const tokenStore = useTokenStore(); 


const ListFields = [
    {
      label: '设备ID',
      prop: 'deviceId',
      type: 'input',
      width: "80px",
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      type: 'input',
      minWidth: "50px",
    },
    {
      label: '设备型号',
      prop: 'deviceModel',
      type: 'input',
      minWidth: "50px",
    },
    {
      label: '类别',
      prop: 'category',
      type: 'input',
      width: "100px",
    },
    {
      label: '供应商',
      prop: 'supplier',
      type: 'input',
      minWidth: "100px",
    },
    {
      label: '供应商评分',
      prop: 'supplierScore',
      type: 'input',
      width: "100px",
    },
    {
      label: '操作',
      prop: 'action',
      slot: true,
      width: "150px"
    },
    {
      label: '查看',
      prop: 'check',
      slot: true,
      width: "250px"
    },
];

const formConfig: DeviceInventoryFormItemConfig[] = [
  {
    type: 'input',
    label: '设备名称',
    prop: 'deviceName',
    placeholder: '请输入设备名称',
  },
  {
    type: 'input',
    label: '设备型号',
    prop: 'deviceModel',
    placeholder: '请输入设备型号',
  },
  {
    type: 'select',
    label: '类别',
    prop: 'category',
    placeholder: '请输入设备类别',
  },
  {
    type: 'input',
    label: '供应商',
    prop: 'supplier',
    placeholder: '请输入供应商名称',
  },
  {
    type: 'input',
    label: '供应商评分',
    prop: 'supplierScore',
    placeholder: '请输入供应商评分',
    inputType: 'number',
  },
];
const categoryList = ref<Category[]>([]);

let deviceInventoryList = ref<DeviceInventory[]>([]);
const formModel = ref<DeviceInventoryModel>({
  deviceId: null,
  deviceName: '',
  deviceModel: '',
  category: '',
  supplier: '',
  supplierScore: null// 如果是 number，可以保留 null，但建议初始化为 0 或 ''
})

const bufferName = [
  { add: "添加设备" },
  { edit: "编辑设备"}
]
const titleName = "设备库存管理";
const searchMessage = ref({
  deviceName:'',
  deviceModel:'',
  category: '',
  supplier: '',
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const title = ref('')
const visibleDrawer = ref(false)
const visibleAppachDrawer = ref(false)


onMounted(async () => {
  await getDataListWithCondition()
  const axiosResponse = await deviceInventoryApi.getCategoryList();
  const responseData: Category[] = axiosResponse.data;
  categoryList.value=responseData
})

const getDataListWithCondition = async () => {
    let params: {
      page: number,
      size: number,
      deviceName?: string | null,
      deviceModel?: string | null,
      category?: string | null,
      supplier?: string | null,
    } = {
        page: pageNum.value,
        size: pageSize.value,
        deviceName: searchMessage.value.deviceName || null,
        deviceModel: searchMessage.value.deviceModel || null,
        category: searchMessage.value.category || null,
        supplier: searchMessage.value.supplier || null,
    }

    try {
        console.log(params)
        const axiosResponse = await deviceInventoryApi.getDeviceInventoryList(params);
        const responseData: DeviceInventoryListResponse = axiosResponse.data;
        
        deviceInventoryList.value = responseData.records;
        console.log("收到库存了")
        console.log(deviceInventoryList.value)
        total.value = responseData.total;
        
    } catch (error) {
        console.error("获取设备库存列表失败:", error);
        ElMessage.error("获取设备库存列表失败");
    }
}
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    console.log('表单开始校验');
    await formRef.value.validate();
    console.log('校验通过，开始提交');

    if (formModel.value.deviceId) {
      await deviceInventoryApi.updateDevice(formModel.value.deviceId, formModel.value);
      ElMessage.success('更新成功');
    } else {
      await deviceInventoryApi.addDevice(formModel.value);
      ElMessage.success('添加成功');
    }
    visibleDrawer.value = false;
    getDataListWithCondition();
  } catch (error) {
    ElMessage.error('表单校验失败，请检查输入项');
  }
};



const clearData = () => {
  formModel.value = {
    deviceId: null,
    deviceName: '',
    deviceModel: '',
    category: '',
    supplier: '',
    supplierScore: null, // 如果你要校验数字范围，这里可以是 null 或 0
  };
};


const showAddDrawer = () => {
    clearData()
    title.value = bufferName[0].add!
    visibleDrawer.value = true
}

const showEditDrawer = async (row: DeviceInventory) => {
    title.value = bufferName[1].edit!;
    formModel.value = { ...row };
    visibleDrawer.value = true;
};

const deletefor = async (id: number) => {
  try {
    await deviceInventoryApi.deleteDevice(id);
    ElMessage.success('删除成功');
    getDataListWithCondition();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请重试");
  }
}

const deleteBox = (id: number) => {
    ElMessageBox.confirm(
        '您确定要删除这条记录吗',
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        deletefor(id)
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '删除取消',
        })
    })
}

const search = () => {
    pageNum.value = 1
    getDataListWithCondition()
    ElMessage('获取成功')
}

const searchWithNoCondition = () => {
    searchMessage.value = { deviceName: '', deviceModel: '', category: '', supplier: '' }
    pageNum.value = 1
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onSizeChange = (size: number) => {
    pageSize.value = size
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onCurrentChange = (num: number) => {
    pageNum.value = num
    getDataListWithCondition()
    ElMessage('获取成功')
}
const handleDrawerClose = () => {
  formRef.value?.clearValidate(); // 清除爆红
}


const contractUrl = ref("")

const currentDeviceName = ref('');
const currentDeviceModel = ref('');
const attachmentOptions = ref<{ label: string; value: string; url: string }[]>([]);
const selectedAttachment = ref<string>('');
const previewImageUrl = ref<string | null>(null);
const currentDeviceProfileId = ref<number | null>(null);
const showAppachDrawer = async (row: DeviceInventory) => {
  currentDeviceName.value = row.deviceName || '';
  currentDeviceModel.value = row.deviceModel || '';
  title.value = `查看附件 - ${currentDeviceName.value}`;
  currentDeviceProfileId.value = row.deviceId;

  attachmentOptions.value = [];
  selectedAttachment.value = '';
  previewImageUrl.value = null;

  visibleAppachDrawer.value = true;

  try {
    if (currentDeviceProfileId.value !== null) {
      const response = await deviceInventoryApi.listAttachmentsByProfileAndType({
        profileId: currentDeviceProfileId.value,
        type: 1,
      });

      attachmentOptions.value = response.data.map((attachment: DeviceAttachment) => ({
        label: attachment.attachmentName,
        value: String(attachment.attachmentId),
        url: attachment.attachmentUrl,
      }));

      console.log(attachmentOptions.value);

      if (attachmentOptions.value.length > 0) {
        selectedAttachment.value = attachmentOptions.value[0].value;
      } else {
        ElMessage.info('该设备暂无附件');
      }
    } else {
      ElMessage.warning('无法获取设备档案ID')
    }
  } catch (error) {
    console.error('获取附件列表失败:', error);
    ElMessage.error('获取附件列表失败，请重试');
    visibleAppachDrawer.value = false;
  }
};

watch(selectedAttachment, (newValue) => {
  const selected = attachmentOptions.value.find(option => option.value === newValue);
  if (selected) {
    previewImageUrl.value = selected.url;
  } else {
    previewImageUrl.value = null;
  }
});

const beforeUploadHandler = ()=>{
  ElMessage('正在加载图片');
}
const uploadSuccess = async (result:any)=>{
  previewImageUrl.value = result.message;
  console.log(previewImageUrl.value);
  ElMessage('添加图片成功');
}

const newAttachment = ref<DeviceAttachmentDTO>({
  deviceProfileId: null,
  attachmentName: '',
  type: 1,
  attachmentUrl: ''
});
const saveUploadFiles = async()=>{
  newAttachment.value.deviceProfileId=currentDeviceProfileId.value;
  newAttachment.value.attachmentName=selectedAttachment.value;
  newAttachment.value.attachmentUrl=previewImageUrl.value;
  console.log(newAttachment.value.attachmentUrl);
  await deviceInventoryApi.saveAttachment(newAttachment.value);
  ElMessage("更新成功");
  visibleAppachDrawer.value = false;
  getDataListWithCondition();
}
</script>

<template>
  <el-card class="page-container">
    <template #header >
        <div class="header">
            <span>{{ titleName }}</span>
            <div class="extra">
                <el-button type="primary" @click="showAddDrawer()">{{ bufferName[0].add }}</el-button>
            </div>
        </div>
    </template>

    <el-form inline>
      <el-form-item label="设备名称:">
        <el-input v-model="searchMessage.deviceName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="设备型号:">
        <el-input v-model="searchMessage.deviceModel" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="类别:">
        <el-input v-model="searchMessage.category" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="供应商:">
        <el-input v-model="searchMessage.supplier" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" @click="search()">搜索</el-button>
         <el-button @click="searchWithNoCondition()">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="deviceInventoryList" style="width: 100%">
      <el-table-column
        v-for="col in ListFields"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :min-width="col.minWidth"
      >
        <template v-if="col.slot" #default="scope">
          <template v-if="col.prop === 'action'">
            <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="showEditDrawer(scope.row)"
            ></el-button>
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="deleteBox(scope.row.deviceId)"
            ></el-button>
          </template>
          <template v-else-if="col.prop === 'check'">
              <el-button
              plain
              type="primary"
              @click="showAppachDrawer(scope.row)"
            >查看附件文件</el-button>
          </template>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
        layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


        <el-drawer 
  v-model="visibleDrawer" 
  :title="title" 
  direction="rtl" 
  size="50%" 
  @close="handleDrawerClose">

      <el-form
  ref="formRef"
  :model="formModel"
  :rules="formRules"
  label-width="120px"
>

    <template v-for="(item, index) in formConfig" :key="index">
      <!-- 输入框类型 -->
      <el-form-item
        v-if="item.type === 'input'"
        :label="item.label"
        :prop="item.prop"
      >
        <el-input
          v-model="formModel[item.prop]"
          :placeholder="item.placeholder"
          :type="item.inputType === 'number' ? 'number' : 'text'"
        ></el-input>
      </el-form-item>

      <!-- 下拉框类型 -->
      <el-form-item
        v-else-if="item.type === 'select'"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-model="formModel[item.prop]"
          :placeholder="item.placeholder"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="option in categoryList"
            :key="option.categoryName"
            :label="option.categoryName"
            :value="option.categoryName"
          />
        </el-select>
      </el-form-item>
    </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </el-form-item>

        <el-upload class="avatar-uploader" 
                    :auto-upload="true" 
                    :show-file-list="false" 
                    action="/api/procedure/monitor/contract/uploadFile"
                    name="file" 
                    :headers="{ 'Authorization': tokenStore.token }" 
                    :on-success="uploadSuccess"
                    :before-upload="beforeUploadHandler"
                    >
                        <img v-if="contractUrl" :src="contractUrl" class="avatar" >
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
          <el-button type="primary" @click="saveUploadFiles()" style="margin: 20px 0 0 0;">保存合同</el-button>
      </el-form>
    </el-drawer>



    <el-drawer v-model="visibleAppachDrawer" :title="title" direction="rtl" size="50%">
      <div style="padding: 20px;">
        <p style="text-align: center;font-size: 1.2em; font-weight: bold; margin-bottom: 15px;">
          设备名称: {{ currentDeviceName }} &nbsp;&nbsp; 设备型号: {{ currentDeviceModel }}
        </p>

        <el-form-item label="选择附件" style="margin-bottom: 20px;">
          <el-select v-model="selectedAttachment" placeholder="请选择附件" style="width: 100%;">
            <el-option
              v-for="item in attachmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <div v-if="previewImageUrl" style="  margin-top: 10px;text-align: center;">
            <el-button type="primary" @click="saveUploadFiles()" style="margin-bottom: 10px;">编辑并保存附件</el-button>
                  <el-upload class="avatar-uploader" 
                    :auto-upload="true" 
                    :show-file-list="false" 
                    action="/api/procedure/attachments/uploadFile"
                    name="file" 
                    :headers="{ 'Authorization': tokenStore.token }" 
                    :on-success="uploadSuccess"
                    :before-upload="beforeUploadHandler"
                    >
                    <img v-if="previewImageUrl" :src="previewImageUrl" class="avatar" >
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
        </div>
        <div v-else style="text-align: center; color: #909399;">
          暂无图片可预览 或 附件非图片类型
        </div>
      </div>
    </el-drawer>


  </el-card>
</template>



<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
  min-width: 50%;
  max-width: 100%; 
  height: auto; display: 
  block; 
  margin: 0 auto;
    :deep() {
        .avatar {
            width: 500px; 
            height: 707px; 
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

:deep(.avatar-uploader .el-upload) {

  background-color: #e0f2f7;
            width: 500px; 
            height: 707px; 
  // overflow: hidden;
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
.my-select {
  width: 250px;
}

.el-table {
  :deep(.el-table__row) {
    height: 20px !important;
  }
  // 如果您还想调整表头高度
  :deep(.el-table__header-wrapper th) {
    height: 20px !important;
  }
}
</style>